package com.it.bigdata.dao;

import com.it.bigdata.domian.TieZi;
import com.it.bigdata.util.Hbasetuils;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.List;

public class TieZiDao {
    //帖子持久化，将一个帖子的内容存储到hbase数据库中
    public void add(TieZi tieZi) throws IOException {
        //获取连接对象，并且根据表名获取表对象
        Connection con = Hbasetuils.getCon();

            //将标题+作者+时间戳作为行键
            byte [] rowKey= Bytes.toBytes(tieZi.getAuthor()+","+tieZi.getTitle()+","+System.currentTimeMillis());
            Table tz= con.getTable(TableName.valueOf("tz"));
            byte[] family = Bytes.toBytes("base_info");
            //获取对插入内容的记录
            Put put=new Put(rowKey);
            if (tieZi.getTitle()!=null&&tieZi.getTitle()!=null&&tieZi.getImage()!=null&&tieZi.getImage().size()>0) {
                //标题列
                put.addColumn(family, Bytes.toBytes("title"), Bytes.toBytes(tieZi.getTitle()));
                //作者列
                put.addColumn(family, Bytes.toBytes("author"), Bytes.toBytes(tieZi.getAuthor()));
                List<String> image = tieZi.getImage();
                StringBuffer sb = new StringBuffer();
                for (String s : image) {
                    sb.append(s + ",");
                }
                String url = sb.toString().substring(0, sb.length() - 1);
                //图片地址列
                put.addColumn(family, Bytes.toBytes("images"), Bytes.toBytes(url));
                tz.put(put);
            }
        con.close();
        tz.close();
    }
}
